package mi.payment.ui.calculator;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.DecimalFormat;

import mi.payment.R;
import mi.payment.ui.base.NumberKeyCalculator;
import mi.payment.ui.base.ParentActivity;

/**
 * @author Created by longx on 2018-03-15.
 */

public class CalculatorActivity extends ParentActivity {

    private TextView tvResult;
    private boolean isCounted = false;  //是否点了等于计算完成
    private StringBuilder allMainInput = new StringBuilder();//用于记录输入的所有的内容，并且计算
    private StringBuilder showNum = new StringBuilder();

    private final static String OPERATOR_ADDITION = "+";
    private final static String OPERATOR_SUBTRACTION = "－";
    private final static String OPERATOR_MULTIPLICATION = "×";
    private final static String OPERATOR_DIVISION = "÷";
    private final static String NUM_0 = "0";
    private final static String SYMBOL_SPOT = ".";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarColor();
        setContentView(R.layout.activity_calculator);
        initView();
    }

    private void getResult() {
        String str = allMainInput.toString();
        if (TextUtils.isEmpty(str)) {
            return;
        }
        if (containsOperator(str)) {
            if (str.contains(OPERATOR_ADDITION)) {
                calculation(OPERATOR_ADDITION, str);
            } else if (str.contains(OPERATOR_SUBTRACTION)) {
                calculation(OPERATOR_SUBTRACTION, str);
            } else if (str.contains(OPERATOR_MULTIPLICATION)) {
                calculation(OPERATOR_MULTIPLICATION, str);
            } else if (str.contains(OPERATOR_DIVISION)) {
                calculation(OPERATOR_DIVISION, str);
            }
        }
    }

    @SuppressLint("DefaultLocale")
    private void calculation(String operator, String data) {
        // 两个String类型的参数
        String param1 = data.substring(0, data.indexOf(operator));
        String param2 = data.substring(data.indexOf(operator) + 1);
        if (TextUtils.isEmpty(param2)) {
            return;
        }
        // 转换后的两个double类型的参数
        double arg1 = Double.parseDouble(param1);
        double arg2 = Double.parseDouble(param2);
        double result = 0;
        switch (operator) {
            case OPERATOR_ADDITION:
                result = CalculatorUtils.add(arg1, arg2);
                break;
            case OPERATOR_SUBTRACTION:
                result = CalculatorUtils.sub(arg1, arg2);
                break;
            case OPERATOR_MULTIPLICATION:
                result = CalculatorUtils.mul(arg1, arg2);
                break;
            case OPERATOR_DIVISION:
                if (TextUtils.equals(NUM_0, param2)) {
                    result = 0;
                } else {
                    result = CalculatorUtils.div(arg1, arg2, 2);
                }
                break;
        }
        allMainInput.delete(0, allMainInput.length());
        allMainInput.append(CalculatorUtils.subZeroAndDot(String.format("%f", result)));
    }

    private void isLastOperatorAndReplaceOrAdd(String operator) {
        String str = allMainInput.toString();
        if (containsOperator(str)) {
            String inputLastOne = str.substring(str.length() - 1, str.length());
            if (equalsOperator(inputLastOne)) {
                allMainInput.replace(str.length() - 1, str.length(), operator);
            } else {
                clear();
                showText("ERROR");
            }
        } else {
            if (TextUtils.isEmpty(str)) {
                allMainInput.append(NUM_0);
                allMainInput.append(operator);
            } else {
                allMainInput.append(operator);
            }
        }
    }

    private void operation(String operator) {
        isCounted = false;
        getResult();
        showTextAndRemoveLastOperatorAndShow(allMainInput.toString());
        isLastOperatorAndReplaceOrAdd(operator);
        showNum.delete(0, showNum.length());
    }

    private NumberKeyCalculator.KeyClickCallback keyClickCallback = new NumberKeyCalculator.KeyClickCallback() {
        @Override
        public void onAdd() {//加
            operation(OPERATOR_ADDITION);
        }

        @Override
        public void onSubtract() {//减
            operation(OPERATOR_SUBTRACTION);
        }

        @Override
        public void onMultiply() {//乘
            operation(OPERATOR_MULTIPLICATION);
        }

        @Override
        public void onDivide() {//除
            operation(OPERATOR_DIVISION);
        }

        @Override
        public void onNumClick(int keyNum) {//数字按键被点击
            if (isCounted) {
                allMainInput.delete(0, allMainInput.length());
            }
            if (TextUtils.equals(showNum, NUM_0)) {
                showNum.delete(0, showNum.length());
                allMainInput.delete(allMainInput.length() - 1, allMainInput.length());
            }
            showNum.append(keyNum);
            boolean isAdd = detectionAmount();
            showText(showNum.toString());
            if (!isAdd) {
                allMainInput.append(keyNum);
            }
            isCounted = false;
        }

        @Override
        public void onDelClick() {//退格按键
            if (TextUtils.isEmpty(allMainInput)) {
                clear();
                return;
            }
            if (isCounted) {
                clear();
                return;
            }
            String inputLastOne = allMainInput.substring(allMainInput.length() - 1, allMainInput.length());
            if (equalsOperator(inputLastOne)) {
                clear();
                return;
            }
            allMainInput.delete(allMainInput.length() - 1, allMainInput.length());
            showNum.delete(showNum.length() - 1, showNum.length());
            if (TextUtils.isEmpty(showNum)) {
                showText(NUM_0);
            } else {
                showText(showNum.toString());
            }
        }

        @Override
        public void onCleanClick() {//清空按键
            clear();
        }

        @Override
        public void onCalResult() {//计算结果
            isCounted = true;
            getResult();
            showTextAndRemoveLastOperatorAndShow(allMainInput.toString());
            showNum.delete(0, showNum.length());
        }

        @Override
        public void onDecimalPoint() {//小数点
            if (isCounted) {
                allMainInput.delete(0, allMainInput.length());
            }
            if (showNum.toString().contains(SYMBOL_SPOT)) {
                return;
            }
            if (TextUtils.isEmpty(showNum)) {
                showNum.append(NUM_0 + SYMBOL_SPOT);
                allMainInput.append(NUM_0 + SYMBOL_SPOT);
            } else {
                showNum.append(SYMBOL_SPOT);
                allMainInput.append(SYMBOL_SPOT);
            }
            showText(showNum.toString());
            isCounted = false;
        }

        @Override
        public void onConfirm() {//确认
            isCounted = true;
            getResult();
            showTextAndRemoveLastOperatorAndShow(allMainInput.toString());
            showNum.delete(0, showNum.length());
            String result = tvResult.getText().toString();
            double resultDouble = Double.parseDouble(result);
            if (resultDouble >= 10000000) {
                showToast(getString(R.string.amount_big));
                return;
            }
            if (resultDouble < 0) {
                showToast(getString(R.string.amount_small));
                return;
            }
            DecimalFormat df = new DecimalFormat("#.00");
            Intent intent = getIntent();
            intent.putExtra("result", df.format(resultDouble));
            setResult(2, intent);
            finish();
        }
    };

    private boolean detectionAmount() {
        String strShowNum = showNum.toString();
        if (strShowNum.contains(SYMBOL_SPOT)) {
            String param = showNum.substring(showNum.indexOf(SYMBOL_SPOT) + 1);
            int paramLength = param.length();
            if (paramLength <= 2) {
                return false;
            } else {
                showNum.delete(showNum.length() - (paramLength - 2), showNum.length());
                return true;
            }
        } else {
            if (strShowNum.length() <= 7) {
                return false;
            } else {//0123456789
                showNum.delete(7, strShowNum.length());
                return true;
            }
        }
    }

    private boolean containsOperator(String str) {
        return str.contains(OPERATOR_ADDITION) || str.contains(OPERATOR_SUBTRACTION) || str.contains(OPERATOR_MULTIPLICATION) || str.contains(OPERATOR_DIVISION);
    }

    private boolean equalsOperator(String str) {
        return TextUtils.equals(str, OPERATOR_ADDITION)
                || TextUtils.equals(str, OPERATOR_SUBTRACTION)
                || TextUtils.equals(str, OPERATOR_MULTIPLICATION)
                || TextUtils.equals(str, OPERATOR_DIVISION);
    }

    private void clear() {
        allMainInput.delete(0, allMainInput.length());
        showNum.delete(0, showNum.length());
        showText(NUM_0);
        isCounted = false;
    }

    private void showText(String text) {
        if (text.length() > 11) {
            tvResult.setTextSize(52 * 11 / text.length());
        } else {
            tvResult.setTextSize(52);
        }
        tvResult.setText(text);
    }

    private void showTextAndRemoveLastOperatorAndShow(String text) {
        if (text.length() > 11) {
            tvResult.setTextSize(52 * 11 / text.length());
        } else {
            tvResult.setTextSize(52);
        }
        if (TextUtils.isEmpty(text)) {
            return;
        }
        String inputLastOne = text.substring(text.length() - 1, text.length());
        if (equalsOperator(inputLastOne)) {
            tvResult.setText(text.substring(0, text.length() - 1));
        } else {
            tvResult.setText(text);
        }
    }

    /**
     * 初始View
     */
    private void initView() {
        NumberKeyCalculator mKeyboard = (NumberKeyCalculator) findViewById(R.id.keyboard);
        tvResult = (TextView) findViewById(R.id.tv_calculator_result);
        RelativeLayout ivBack = (RelativeLayout) findViewById(R.id.rl_title);
        mKeyboard.setKeyClickCallback(keyClickCallback);
        ivBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_title:
                finish();
                break;
        }
    }
}